package viewset.com.kkcamera.view.image.opengl.filter.graph

import android.content.Context
import android.opengl.GLES20
import com.chan.mediacamera.camera.filter.BaseFilter
import com.chan.mediacamera.util.MatrixTools
import com.chan.mediacamera.util.OpenGlUtils
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.ShortBuffer

/**
 * 立方体
 */
class CubeFillter(var context: Context) : BaseFilter(context) {

    private var mVertexCount: Int? = null
    private var vertexBuffer: FloatBuffer? = null
    private var colorBuffer: FloatBuffer? = null
    private var indexBuffer: ShortBuffer? = null

    private lateinit var matrixTools: MatrixTools

    internal val cubePositions = floatArrayOf(-1.0f, 1.0f, 1.0f, //正面左上0
            -1.0f, -1.0f, 1.0f, //正面左下1
            1.0f, -1.0f, 1.0f, //正面右下2
            1.0f, 1.0f, 1.0f, //正面右上3
            -1.0f, 1.0f, -1.0f, //反面左上4
            -1.0f, -1.0f, -1.0f, //反面左下5
            1.0f, -1.0f, -1.0f, //反面右下6
            1.0f, 1.0f, -1.0f)//反面右上7

    internal val index = shortArrayOf(0, 3, 2, 0, 2, 1, //正面
            0, 1, 5, 0, 5, 4, //左面
            0, 7, 3, 0, 4, 7, //上面
            6, 7, 4, 6, 4, 5, //后面
            6, 3, 7, 6, 2, 3, //右面
            6, 5, 1, 6, 1, 2     //下面
    )

    internal var color = floatArrayOf(0f, 1f, 1f, 1f, 0f, 1f, 1f, 1f, 0f, 1f, 1f, 1f, 0f, 1f, 1f, 1f, 1f, 0f, 1f, 1f, 1f, 0f, 1f, 1f, 1f, 0f, 1f, 1f, 1f, 0f, 1f, 1f)

    override fun onCreateShare() {
        mContext?.let {
            mVertexShader = OpenGlUtils.loadShareFromAssetsFile("graph/cube_shader_vertex.glsl", it.resources)
            mFragmentShader = OpenGlUtils.loadShareFromAssetsFile("graph/cube_shader_fragment.glsl", it.resources)
        }
        matrixTools = MatrixTools()
    }

    override fun initBuffer() {
        //顶点着色器
        val bb = ByteBuffer.allocateDirect(
                cubePositions.size * 4)
        bb.order(ByteOrder.nativeOrder())
        //将坐标数据转换为FloatBuffer，用以传入给OpenGL ES程序
        vertexBuffer = bb.asFloatBuffer()
        vertexBuffer?.put(cubePositions)
        vertexBuffer?.position(0)

        //颜色着色器
        val dd = ByteBuffer.allocateDirect(
                color.size * 4)
        dd.order(ByteOrder.nativeOrder())
        colorBuffer = dd.asFloatBuffer()
        colorBuffer?.put(color)
        colorBuffer?.position(0)

        //链接
        val cc = ByteBuffer.allocateDirect(index.size * 2)
        cc.order(ByteOrder.nativeOrder())
        indexBuffer = cc.asShortBuffer()
        indexBuffer?.put(index)
        indexBuffer?.position(0)

        //多少个点
        mVertexCount = cubePositions.size / 3
    }

    override fun onSizeChanged(width: Int, height: Int) {
        GLES20.glViewport(0, 0, width, height)

        GLES20.glEnable(GLES20.GL_DEPTH_TEST)

        //计算宽高比
        val ratio = width.toFloat() / height
    }
}